package com.joysuch.wwyt.mh.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joysuch.wwyt.common.enums.WfProcessStatusEnum;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.entity.MhAlarmMessage;
import com.joysuch.wwyt.mh.entity.MhAlarmRecord;
import com.joysuch.wwyt.mh.enums.AlarmRecordStateEnum;
import com.joysuch.wwyt.mh.repository.MhAlarmMessageDao;
import com.joysuch.wwyt.mh.service.MhAlarmMessageService;
import com.joysuch.wwyt.mh.service.MhAlarmRecordService;
import com.joysuch.wwyt.monitoringcenter.service.MonitoringCenterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.joysuch.wwyt.common.enums.WfProcessStatusEnum.FINISHED;

/**
 * 获取流程状态更新alarmRecord
 * @author Leong
 * @date 2022/9/20 18:46
 */
@Slf4j
@Component
public class AlarmRecordTask {

    @Resource
    private MhAlarmRecordService mhAlarmRecordService;

    @Resource
    private BaseConfigService baseConfigService;

    @Resource
    private RedisClient redisClient;

    @Resource
    private MhAlarmMessageDao mhAlarmMessageDao;

    @Resource
    private MonitoringCenterService monitoringCenterService;

    @Scheduled(initialDelay = 10000, fixedDelay = 10 * 1000)
    public void mobileGasAccess() {
        BaseConfig config = baseConfigService.findFirstConfig(BaseConfigCodes.OPEN_GRADE_ALARM);
        if (config == null || "0".equals(config.getValue())) {
            return;
        }
        List<MhAlarmRecord> list = mhAlarmRecordService.list(new QueryWrapper<MhAlarmRecord>().eq("state", AlarmRecordStateEnum.YES.getValue())
                .isNotNull("alarm_code").eq("delete_flag", DeleteFlag.EFFECTIVE.getCode()));
        log.info("分级报警状态同步列表： {}", list.size());
        List<String> removeKeys = new ArrayList<>();
        List<MhAlarmMessage> mhList = new ArrayList<>();
        list.forEach(each -> {
            BaseConfig ipConfig = baseConfigService.findByTenentIdAndOrgCodeAndCode2(each.getTenentId(), each.getOrgCode(), BaseConfigCodes.ZD_ProcessDefKeyNew);
            if (ipConfig != null) {
                String procDefKey = ipConfig.getValue();
                String processInsStatusKey = String.format(BaseConfigCodes.WORKFLOW_PROCESS_INS_STATUS_KEY, procDefKey, each.getAlarmCode());
                String status = redisClient.get(processInsStatusKey);
                if (StringUtils.isNotBlank(status)) {
                    if (FINISHED.getCode().equals(status)) {
                        each.setState(AlarmRecordStateEnum.NO.getValue());
                        mhAlarmRecordService.updateById(each);
                        //更新通知
                        MhAlarmMessage one = mhAlarmMessageDao.findById(each.getAlarmMessageId()).orElse(null);
                        if (one != null && one.getState() != null && one.getState() != 2) {
                            one.setState(2);
                            one.setRemark("流程同步处理");
                            one.setHandleTime(LocalDateTime.now());
                            one.setAlarmReason("流程同步处理");
                            mhList.add(one);
                        }
                    }
                    if (WfProcessStatusEnum.getAllStatus().contains(status)) {
                        removeKeys.add(processInsStatusKey);
                    }
                }
            }
        });
        if (CollectionUtils.isNotEmpty(mhList)){
            mhAlarmMessageDao.saveAll(mhList);
            monitoringCenterService.handlingHazardAlarms(mhList);
        }
        removeKeys.forEach(each -> redisClient.removeKey(each));
    }
}
